package com.hanserwei.community.manager;

import com.aliyun.oss.OSS;
import com.hanserwei.community.enums.ErrorCodeEnum;
import com.hanserwei.community.exception.ApiException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;

@Component
@RequiredArgsConstructor
@Slf4j
public class OssManager {

    private final OSS ossClient;

    @Value("${aliyun.oss.bucket-name}")
    private String bucketName;

    @Value("${aliyun.oss.host}")
    private String host;

    /**
     * 上传文件
     *
     * @param filePath 文件路径，尽可能唯一
     * @param file     文件
     * @return 文件访问地址
     */
    public String uploadFile(String filePath, File file) {
        try {
            filePath = filePath + "/" + file.getName();
            ossClient.putObject(bucketName, filePath, file);
            return host + filePath;
        } catch (Exception e) {
            log.error("上传文件失败", e);
            throw new ApiException(ErrorCodeEnum.SYSTEM_ERROR, "OSS上传文件失败");
        }
    }

    // TODO: 删除文件
}
